﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.Threading;
using System.Resources;
using System.Globalization;

using System.IO;
using TrainingCenterSystem;
using TrainingCenterSystem.UserManagement;
using TrainingCenterSystem.Utils;

namespace TrainingCenterWinClient.Forms
{
    public partial class LoginForm : Form
    {
        #region private members

        private TrainingCenter _trainingCenter;
        private ResourceManager _langResMgr;
        private ResourceManager _sysResMgr;
        private string _defaultUserFilePath;
        #endregion

        #region constructor(s)
        public LoginForm(TrainingCenter trainingCenter)
        {
            InitializeComponent();

            _trainingCenter = trainingCenter;
            this.UpdateLanguage(_trainingCenter.CurrentLanguageID);
            this.initSystemResources();
            this.searchUserFile();
            this.initForm();
        }
        #endregion

        #region methods

        private void initForm()
        {
            if (_trainingCenter.IsBasicVersion)
            {
                this.btnRegister.Enabled = false;
                this.txtUsername.Enabled = false;
                this.txtPassword.Enabled = false;
            }
        }
        /// <summary>
        /// Initializes the UI language
        /// </summary>
        /// <param name="langID">The ID of the selected language</param>
        private void UpdateLanguage(string langID)
        {
            try
            {
                // Set Language
                Thread.CurrentThread.CurrentUICulture = new CultureInfo(langID);

                // Init ResourceManager for languages
                _langResMgr =
                    new ResourceManager("TrainingCenterWinClient.ReStrings",
                    typeof(LoginForm).Assembly);
                
                // assign localized strings to UI
                this.lblUsername.Text = _langResMgr.GetString("LoginForm_Username");
                this.lblPassword.Text = _langResMgr.GetString("LoginForm_Password");
                this.btnLogin.Text = _langResMgr.GetString("LoginForm_btnLogin");
                this.btnRegister.Text = _langResMgr.GetString("LoginForm_btnRegister");                
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// Initializes the system resources, i.e. loads the default path of the user file.
        /// </summary>
        private void initSystemResources()
        {
            // Init ResourceManager for system resources
            _sysResMgr =
                new ResourceManager("TrainingCenterWinClient.SystemResources",
                typeof(LoginForm).Assembly);

            _defaultUserFilePath = _sysResMgr.GetString("defaultUserFileFullPath");

        }

        /// <summary>
        /// Determines whether the user file already exists. If not, then a new user file is created.
        /// </summary>
        private void searchUserFile()
        {
            if (!File.Exists(_defaultUserFilePath))
                this.writeUserFile();

            this.readUserFile();
        }

        /// <summary>
        /// Reads the existing users from an xml-file. It also reads a list of supervisors waiting for approval.
        /// </summary>
        private void readUserFile()
        {
            UserFileReader reader = new UserFileReader();
            reader.read(_defaultUserFilePath);
            _trainingCenter.AvailableUsers = reader.Users;
            _trainingCenter.ApprovalList = reader.ApprovalList;
        }

        /// <summary>
        /// Writes te initial user file
        /// </summary>
        private void writeUserFile()
        {            
            UserFileWriter ufw = new UserFileWriter(_defaultUserFilePath,this.createInitialUsers(),null);
        }

        /// <summary>
        /// Creates the initial list of users
        /// </summary>
        /// <returns>ArrayList of users</returns>
        /// <remarks>This method is only used initially, i.e. when no user file exists yet.</remarks>
        private ArrayList createInitialUsers()
        {
            ArrayList users = new ArrayList(); 
            users.Add(new Supervisor("001", "sup1","test@test.se"));
            users.Add(new Student("002", "stu1", "test@test.se"));
            return users;
            
        }
        #endregion

        private void btnLogin_Click(object sender, EventArgs e)
        {
            // for dev+test only, will be removed later
            this.txtUsername.Text = "sup1";
            this.txtPassword.Text = "testt";

            //if ((this.txtUsername.Text.Length == 0) || (this.txtPassword.Text.Length == 0))
            //    return;

            // search user
            string username = this.txtUsername.Text;
            string pwd = this.txtPassword.Text;
            User aUser=null;

            // search the user
            for (int i = 0; i < _trainingCenter.AvailableUsers.Count; i++)
            {
                if (((User)_trainingCenter.AvailableUsers[i]).Username == username)
                {
                    aUser = (User)_trainingCenter.AvailableUsers[i];
                    break;
                }
            }

            if (aUser != null) // if user exists
            {
                if (aUser.Password == pwd) // if password is correct
                {
                    _trainingCenter.CurrentUser = aUser;
                    MainForm mf = new MainForm(_trainingCenter, this);
                    mf.Show();
                    this.Hide();
                }
                else // if password is incorrect
                {
                }
            }
            else // if user does not exist
            {
            }
        }

        private void btnRegister_Click(object sender, EventArgs e)
        {
            RegisterForm registerForm = new RegisterForm(_trainingCenter, _defaultUserFilePath);
            registerForm.ShowDialog();
        }
    }
}
